package com.hj.security.oauth.client.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class OauthConfig {
    //在gitee上申请的clientId和clientSecret
    private static final String GITEE_CLIENT_ID = "6f68439b4724e54d88adc074cf0408d2067f5bad0379b2087999b27b29e7199f";
    private static final String GITEE_CLIENT_SECRET= "7bb145704e4e50185b05c0952bd3c974f6d96765256bf897b27545f6280cfef5";


    //配置httpSecurity
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeHttpRequests(request->request.anyRequest().authenticated())
                .oauth2Login(Customizer.withDefaults())
                .csrf(c->c.disable());
        return httpSecurity.build();
    }
    //通过java代码配置gitee的clientRegistration,也可以放在配置文件中配置
    @Bean
    public ClientRegistrationRepository clientRegistrationRepository() {
        ClientRegistration giteeClientRegistration = ClientRegistration.withRegistrationId("gitee")
                .clientId(GITEE_CLIENT_ID)
                .clientSecret(GITEE_CLIENT_SECRET)
                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
                //OAuth2LoginAuthenticationFilter过滤器会拦截/login/oauth2/code/*
                //不需要在客户端中自定义该方法的逻辑
                .redirectUri("http://127.0.0.1:7199/login/oauth2/code/gitee")
                .scope("user_info")
                //gitee默认的授权地址
                .authorizationUri("https://gitee.com/oauth/authorize")
                //gitee默认的code换token地址
                .tokenUri("https://gitee.com/oauth/token")
                //gitee默认的获取用户信息的地址
                .userInfoUri("https://gitee.com/api/v5/user")
                .userNameAttributeName("id")
                .build();

        return new InMemoryClientRegistrationRepository(giteeClientRegistration);
    }
}